<?php

namespace Admin\Controller;
use Common\Model\AuthRuleModel;
/**
 * 权限组
 */
class AuthGroupController extends CommonController {

    /**
     * 权限列表
     */
    public function index() {
        $title=I('title');
        if($title)
        {
            //菜单名搜索
            $map['title']=array('like','%'.$title.'%');
            $this->assign('title',$title);        
        }        
        $list = $this->lists("AuthGroup",$map);
        int_to_string($list);
         $this->meta_title = '权限管理';        
        $this->assign("_list", $list);
        $this->display();
    }

    /**
     * 权限组添加
     */
    public function add() {
        if (IS_POST) {
            $AuthGroup = D('Common/AuthGroup');
            $data = $AuthGroup->create();
            if ($data) {
                if (empty($data['id'])) {
                    $r = $AuthGroup->add();
                } else {

                    $r = $AuthGroup->save();
                }
                if ($r === false) {
                    $this->error('操作失败' . $AuthGroup->getError());
                } else {
                    $this->success('操作成功!', U('index'));
                }
            } else {
                $this->error('操作失败' . $AuthGroup->getError());
            }
        }        
        $this->meta_title = '添加权限组';     
        $this->display("edit");
    }

    /**
     * 权限组编辑
     */
    public function edit() {
        $id = I("id");
        $AuthGroup = D('Common/AuthGroup');
        if (IS_POST) {
            $data = $AuthGroup->create();
            if ($data) {
                if (empty($data['id'])) {
                    $r = $AuthGroup->add();
                } else {
                    $r = $AuthGroup->save();
                }
                if ($r === false) {
                    $this->error('操作失败' . $AuthGroup->getError());
                } else {
                    $this->success('操作成功!', U('index'));
                }
            } else {
                $this->error('操作失败' . $AuthGroup->getError());
            }
        }
        $info = $AuthGroup->where(array("id" => $id))->find();
        $this->meta_title = '编辑权限组';             
        $this->assign("info", $info);
        $this->display();
    }

    /**
     * 设置访问权限
     */
    public function access() {
        //更新角色表
        $this->updateRules();
        $AuthGroup=D("Common/AuthGroup");
        $auth_group = $AuthGroup->getAuthGroupFiled(array('status'=>array('egt','0')),'id,id,title,rules');
        $node_list   = D("Common/Menu")->getReturnNode();
    
        $AuthRule=D("Common/AuthRule");
        $map         = array('module'=>'admin','type'=>AuthRuleModel::RULE_MAIN,'status'=>1);
        $main_rules  =  $AuthRule->getAuthRuleFiled($map,"name,id");
       
        $map         = array('module'=>'admin','type'=>AuthRuleModel::RULE_URL,'status'=>1);
        $child_rules = $AuthRule->getAuthRuleFiled($map,"name,id");
       
        $this->assign('main_rules', $main_rules);
        $this->assign('auth_rules', $child_rules);
        $this->assign('node_list',  $node_list);
        $this->assign('auth_group', $auth_group);
  
        $this->assign('this_group', $auth_group[(int)$_GET['group_id']]);
        $this->meta_title = '访问授权';
        $this->display();
    }
    /**
     * 授权用户
     */
    public function group(){
         $uid            =   I('uid');
        $auth_groups    =   D('Common/AuthGroup')->getGroups();
   
        $user_groups    =   D('Common/AuthGroup')->getUserGroup($uid);

       $ids = array();
        foreach ($user_groups as $value) {
            $ids[] = $value['group_id'];
        }
        $nickname       =   D('Common/Member')->getNickName($uid);
         $this->assign('nickname',   $nickname);
         $this->assign('auth_groups',$auth_groups);
         $this->assign('user_groups',implode(',',$ids));
        $this->meta_title = '授权管理';
        $this->display();
    }
    
    
    /***
     * 权限写入权限组中
     */
    public function writeGroup(){
       
        if(isset($_POST['rules'])){
            sort($_POST['rules']);
            $_POST['rules']  = implode( ',' , array_unique($_POST['rules']));
        }
        //$_POST['module'] =  'admin';
        //$_POST['type']   =  AuthGroupModel::TYPE_ADMIN;
        $AuthGroup       =  D('AuthGroup');
        $data = $AuthGroup->create();
        if ( $data ) {
            if ( empty($data['id']) ) {
              
                
                $r = $AuthGroup->add();
              
            }else{
                
                $r = $AuthGroup->save();
               
            }
            if($r===false){
                $this->error('操作失败'.$AuthGroup->getError());
            } else{
                $this->success('操作成功!',U('index'));
            }
        }else{
            $this->error('操作失败'.$AuthGroup->getError());
        }
    }
    /**
     * 更新角色表
     */
    public function updateRules() {
        //获取菜单列表。加入到角色表中,更新与删除
        $nodes=D("Common/Menu")->getReturnNode(false);  //获取所有节点
        $map      = array('type'=>array('in','1,2'));//status全部取出,以进行更新
        //需要更新和删除的节点必然位于$rules
        $map      = array('module'=>'admin','type'=>array('in','1,2'));
        $AuthRule=D("Common/AuthRule");
        $rules   =  $AuthRule->getAuthRuleList($map);
       
         $data     = array();//保存需要插入和更新的新节点
        foreach ($nodes as $value){
            $temp['name']   = $value['url'];
            $temp['title']  = $value['title'];
            $temp['module'] = 'admin';
            if($value['pid'] >0){
                $temp['type'] = AuthRuleModel::RULE_URL;
            }else{
                $temp['type'] = AuthRuleModel::RULE_MAIN;
            }
            $temp['status']   = 1;
            $data[strtolower($temp['name'].$temp['module'].$temp['type'])] = $temp;//去除重复项
        }
               
         $update = array();//保存需要更新的节点
        $ids    = array();//保存需要删除的节点的id
       foreach ($rules as $index=>$rule){
            $key = strtolower($rule['name'].$rule['module'].$rule['type']);
            
            if ( isset($data[$key]) ) {//如果数据库中的规则与配置的节点匹配,说明是需要更新的节点
                $data[$key]['id'] = $rule['id'];//为需要更新的节点补充id值
                $update[] = $data[$key];
                unset($data[$key]);
                unset($rules[$index]);
                unset($rule['condition']);
                $diff[$rule['id']]=$rule;
            }elseif($rule['status']==1){
                $ids[] = $rule['id'];
            }
        }

        if ( count($update) ) {
            foreach ($update as $k=>$row){
                if ( $row!=$diff[$row['id']] ) {
                    $AuthRule->saveData(array('id'=>$row['id']),$row);
                }
            }
        }
      
        if ( count($ids) ) {
            $AuthRule->saveData(array( 'id'=>array('IN',implode(',',$ids)) ),array('status'=>-1));
            //删除规则是否需要从每个用户组的访问授权表中移除该规则?
        }
        if( count($data) ){
            $AuthRule->addDataAll(array_values($data));
        }
        
        if ( $AuthRule->getDbError() ) {
            trace('['.__METHOD__.']:'.$AuthRule->getDbError());
            return false;
        }else{
            return true;
        }
        
        
    }
    /**
     * 添加访问组中
     */
    public function addToGroup(){
       
        $uid = I('uid');
        $gid = I('group_id');
        if( empty($uid) ){
            $this->error('参数有误');
        }
        $AuthGroup = D('Common/AuthGroup');
        if(is_numeric($uid)){
            if ( is_administrator($uid) ) {
                $this->error('该用户为超级管理员');
            }
            if( !M('Member')->where(array('uid'=>$uid))->find() ){
                $this->error('用户不存在');
            }
        }

        if( $gid && !$AuthGroup->checkGroupId($gid)){
            $this->error($AuthGroup->error);
        }
        if ( $AuthGroup->addToGroup($uid,$gid) ){
            $this->success('操作成功',U('Users/index'));
        }else{
            $this->error($AuthGroup->getError());
        }
    }
    /*
     * 删除
     */
    public function del() {
        $model = D("AuthGroup");   
        $id = I('id');
        if ($model->where(array("id" => $id))->delete()) {
            $this->success("删除成功");
        } else {
            $this->error("删除失败");
        }
    }
}
